package com.ld.rightsSystem.mapper;

import com.ld.rightsSystem.pojo.TPermission;
import com.ld.rightsSystem.pojo.TRole;
import com.ld.rightsSystem.pojo.TUser;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户信息表 Mapper 接口
 * </p>
 *
 * @author lhb
 * @since 2023-12-27
 */
@Repository
public interface TUserRepository extends JpaRepository<TUser,Long> {

    @Transactional
    @Modifying
    @Query(value = "insert into auth.t_user (user_name,phone,password,create_by,remark) " +
            "values (:#{#tUser.userName},:#{#tUser.phone},:#{#tUser.password}," +
            ":#{#tUser.createBy},:#{#tRole.remark})",nativeQuery = true)
    int insert(@Param("tUser")TUser tUser);

    @Transactional
    @Modifying
    @Query(value = "update auth.t_user set user_name=:#{#tUser.userName}," +
            "phone=:#{#tUser.phone},update_by=:#{#tUser.updateBy}," +
            "remark=:#{#tUser.remark},update_time=:#{#tUser.updateTime}" +
            "where user_id=:#{#tUser.userId}",nativeQuery = true)
    int updateTUser(@Param("tUser") TUser tUser);

    @Transactional
    @Modifying
    @Query(value = "update auth.t_user set password=:password where user_name=:userName",nativeQuery = true)
    int updateTUserPasswordByUserName(@Param("userName")String userName,@Param("password") String password);

    @Query(value = "select * from auth.t_user where user_name=:userName",nativeQuery = true)
    TUser findTUserByUserName(@Param("userName")String userName);

    @Query(value = "select user_id from auth.t_user where del_status=0 and user_name=:userName",nativeQuery = true)
    Long findUserIdByUserName(@Param("userName")String userName);

    @Transactional
    @Modifying
    @Query(value = "update auth.t_user set del_status=1,update_by=:updateBy,update_time=:updateTime where user_id=:userId and del_status=0",nativeQuery = true)
    int deleteTUserByUserId(@Param("userId")Long userId, @Param("updateBy") String updateBy, @Param("updateTime") Date updateTime);

    TUser findTUserByUserIdAndUserName(Long userId,String userName);

    TUser findTUserByUserId(Long userId);

    @Query(value = "select user_id,user_name,phone,remark,create_by,create_time,update_by,update_time,status,del_status from auth.t_user where del_status=0",nativeQuery = true)
    List<TUser> findTUsersPageable(PageRequest pageRequest);

    @Query(value = "select password from auth.t_user where del_status=0 and user_name=:userName",nativeQuery = true)
    String findTUserPasswordByUserName(@Param("userName")String userName);
}
